<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('workReport:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="工单编号">
                <a-select
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  allowClear
                  style="width: 100%"
                  v-model="queryParam.workOrderId"
                  placeholder="请选择工单">
                  <a-select-option v-for="(item,index) in list.orderIdList" :key="index" :value="item.id">{{ item.workOrderNo }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="工序名称">
                <a-select
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  allowClear
                  style="width: 100%"
                  v-model="queryParam.stepId"
                  placeholder="请选择工序">
                  <a-select-option v-for="(item,index) in list.stepIdList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="工序状态">
                <a-select
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  allowClear
                  style="width: 100%"
                  v-model="queryParam.status"
                  placeholder="请选择工序状态">
                  <a-select-option v-for="(item,index) in list.statusList" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="生产人员">
                <user-select v-model="queryParam.productionUser" allow-clear placeholder="请选择生产人员"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="开始时间">
                  <a-date-picker style="width: 100%" placeholder="请选择开始时间" v-model="queryParam.startTimeDate" @change="onChangestartTime"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="结束时间">
                  <a-date-picker style="width: 100%" placeholder="请选择结束时间" v-model="queryParam.endTimeDate" @change="onChangeendTime"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="8" :sm="24" >
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" >查询</a-button>
                <a-button style="margin-left: 8px" @click="allNull();$refs.table.refresh(true)">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        :scroll="{ x: 1500 }"
        ref="table"
        :columns="columns"
        :components="this.comp"
        bordered
        :data="loadData"
        :alert="options.alert"
        :rowKey="(record) => record.id"
        :rowSelection="options.rowSelection"
      >
        <template class="table-operator" slot="operator" v-if="hasPerm('workReport:add')" >
          <a-button type="primary" v-if="hasPerm('workReport:add')" icon="plus" @click="$refs.addForm.add()">新增报工表</a-button>
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('workReport:delete')" @click="batchDelete"><a-icon type="delete"/>批量删除</a-button>
          <x-down
            v-if="hasPerm('workReport:export')"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <span slot="mulBadItemScopedSlots" slot-scope="text">
          {{ 'bad_item' | dictType(text) }}
        </span>
        <span slot="workOrderIdScopedSlots" slot-scope="text">
          {{ '${column.dictTypeCode}' | dictType(text) }}
        </span>
        <span slot="taskIdScopedSlots" slot-scope="text">
          {{ '${column.dictTypeCode}' | dictType(text) }}
        </span>
        <span slot="statusScopedSlots" slot-scope="text">
          {{ '${column.dictTypeCode}' | dictType(text) }}
        </span>
        <span slot="mulBadItemScopedSlots" slot-scope="text">
          <a-tag color="red" v-for="(item,index) in text?getDicName(text.split(';'), mulBadItemData):'' " :key="index">{{ item.name }}</a-tag>
        </span>
        <span slot="statusScopedSlots" slot-scope="text">
          <a-tag v-if="text === -1" >未开始</a-tag>
          <a-tag v-if="text === 0" color="green">执行中</a-tag>
          <a-tag v-if="text === 1" color="red">已结束</a-tag>
        </span>
        <span slot="approvalStatus" slot-scope="text">
          <a-tag v-if="text === 0" >未审批</a-tag>
          <a-tag v-if="text === 1" color="green">已审批</a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('workReport:detail')" @click="$refs.detail.detail(record)">查看</a>
          <a-divider type="vertical" v-if="hasPerm('workReport:detail') & hasPerm('workReport:delete')"/>
          <a v-if="hasPerm('workReport:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('workReport:edit') & hasPerm('workReport:delete')"/>
          <a v-if="hasPerm('workReport:approval')" @click="singleApproval(record)">审批</a>
          <a-divider type="vertical" v-if="hasPerm('workReport:approval') & hasPerm('workReport:delete')"/>
          <a-popconfirm v-if="hasPerm('workReport:delete')" placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <add-form ref="addForm" @ok="handleOk" />
      <edit-form ref="editForm" @ok="handleOk" />
      <detail ref="detail" @ok="handleOk" />

    </a-card>
  </div>
</template>
<script>
import { workStepList } from '@/api/modular/main/workstep/workStepManage'
import { taskList } from '@/api/modular/main/task/taskManage'
  import { STable, XDown } from '@/components'
  import moment from 'moment'
  import { workReportPage, workReportDelete, workReportExport, workReportApproval } from '@/api/modular/main/workreport/workReportManage'
  import addForm from './addForm.vue'
  import editForm from './editForm.vue'
  import detail from './detail.vue'
  import { getDicName } from '@/utils/util'
  import dragMixin from '@/mixins/drag/index'
  import '@/mixins/drag/drag.css'
  import { workOrderList } from '@/api/modular/main/workorder/workOrderManage'
  import UserSelect from '@/components/MyComp/UserSelect'

  export default {
    components: {
      detail,
      STable,
      addForm,
      editForm,
      XDown,
      UserSelect
    },
    mixins: [ dragMixin ],
    data () {
      return {
        // 不良品字典
        mulBadItemData: [],
        list: {
          statusList: [
            { 'name': '未开始', code: -1 },
            { 'name': '执行中', code: 0 },
            { 'name': '已结束', code: 1 }
          ],
          stepIdList: [],
          orderIdList: []
        },
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 表头
        columns: [
          {
            title: '工单编号',
            align: 'center',
            dataIndex: 'workOrderNo',
            width: 200,
              ellipsis: true
          },
          {
            title: '工序名称',
            align: 'center',
            dataIndex: 'stepName',
            width: 150,
            ellipsis: true
          },
          {
            title: '工序状态',
            align: 'center',
            dataIndex: 'status',
            width: 100,
            ellipsis: true,
            scopedSlots: { customRender: 'statusScopedSlots' }
          },
          {
            title: '生产人员',
            align: 'center',
            dataIndex: 'productionUserName',
            width: 110,
            ellipsis: true
          },
          {
            title: '报工数',
            align: 'center',
            dataIndex: 'reportNum',
            width: 80,
            ellipsis: true
          },
          {
            title: '良品数',
            align: 'center',
            dataIndex: 'goodNum',
            width: 80,
            ellipsis: true
          },
          {
            title: '不良品数',
            align: 'center',
            dataIndex: 'badNum',
            width: 80,
            ellipsis: true
          },
          {
            title: '开始时间',
            align: 'center',
            dataIndex: 'startTime',
            width: 130,
            ellipsis: true
          },
          {
            title: '结束时间',
            align: 'center',
            dataIndex: 'endTime',
            width: 130,
            ellipsis: true
          },
          {
            title: '工作时长',
            align: 'center',
            dataIndex: 'workTime',
            width: 100,
            ellipsis: true
          },
          {
            title: '审批状态',
            align: 'center',
            dataIndex: 'approval',
            width: 100,
            ellipsis: true,
            scopedSlots: { customRender: 'approvalStatus' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          Object.assign(parameter, this.switchingDate())
          if (parameter.mulBadItem) {
            parameter.mulBadItem = parameter.mulBadItem.join(';')
          }
          return workReportPage(parameter).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        options: {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
      }
    },
    created () {
      this.visible = true

      taskList().then(res => {
        this.list.taskIdList = res.data
      })
      workOrderList().then(res => {
        this.list.orderIdList = res.data
      })
      workStepList().then(res => {
        this.list.stepIdList = res.data
      })

      if (this.hasPerm('workReport:edit') || this.hasPerm('workReport:delete')) {
        this.columns.push({
          title: '操作',
          width: 300,
          align: 'center',
          ellipsis: true,
          fixed: 'right',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
      const mulBadItemOption = this.$options
      this.mulBadItemData = mulBadItemOption.filters['dictData']('bad_item')
    },
    methods: {

      singleApproval(values) {
        let message = '审批成功'
        if (values.approval === 1) {
           message = '审批已取消'
        }
        workReportApproval(values).then((res) => {
          if (res.success) {
            this.$message.success(message)
            this.$refs.table.clearRefreshSelected()
            this.confirmLoading = false
            this.$emit('ok', values)
          } else {
            this.$message.error(res.message)
          }
        }).finally((res) => {
          this.confirmLoading = false
        })
      },
      getDicName,
      moment,
      allNull() {
       this.queryParam = {}
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
      /**
       * 查询参数组装
       */
      switchingDate () {
        const queryParamendTime = this.queryParam.endTimeDate
        if (queryParamendTime != null) {
            this.queryParam.endTime = moment(queryParamendTime).format('YYYY-MM-DD')
            if (queryParamendTime.length < 1) {
                delete this.queryParam.endTime
            }
        } else {
          this.queryParam.endTime = null
        }
        const queryParamstartTime = this.queryParam.startTimeDate
        if (queryParamstartTime != null) {
            this.queryParam.startTime = moment(queryParamstartTime).format('YYYY-MM-DD')
            if (queryParamstartTime.length < 1) {
                delete this.queryParam.startTime
            }
        } else {
          this.queryParam.startTime = null
        }

        const obj = JSON.parse(JSON.stringify(this.queryParam))
        return obj
      },
      /**
       * 单个删除
       */
      singleDelete (record) {
        const param = [{ 'id': record.id }]
        this.workReportDelete(param)
      },
      /**
       * 批量删除
       */
      batchDelete () {
        const paramIds = this.selectedRowKeys.map((d) => {
            return { 'id': d }
        })
        this.workReportDelete(paramIds)
      },
      workReportDelete (record) {
        workReportDelete(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败') // + res.message
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      onChangeendTime(date, dateString) {
        this.endTimeDateString = dateString
      },
      onChangestartTime(date, dateString) {
        this.startTimeDateString = dateString
      },
      /**
       * 批量导出
       */
      batchExport () {
        const paramIds = this.selectedRowKeys.map((d) => {
            return { 'id': d }
        })
        workReportExport(paramIds).then((res) => {
            this.$refs.batchExport.downloadfile(res)
        })
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
</style>
